<template>
  <el-dialog
    v-model="dialogVisible"
    title="标签统计信息"
    width="1000px"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <div v-loading="loading" class="statistics-content">
      <!-- 基础统计 -->
      <div class="basic-statistics">
        <h3>基础统计</h3>
        <div class="stat-cards">
          <div class="stat-card">
            <div class="stat-value">{{ statistics?.totalTags || 0 }}</div>
            <div class="stat-label">总标签数</div>
          </div>
          <div class="stat-card enabled">
            <div class="stat-value">{{ statistics?.enabledTags || 0 }}</div>
            <div class="stat-label">启用标签</div>
          </div>
          <div class="stat-card disabled">
            <div class="stat-value">{{ statistics?.disabledTags || 0 }}</div>
            <div class="stat-label">禁用标签</div>
          </div>
          <div class="stat-card used">
            <div class="stat-value">{{ statistics?.usedTags || 0 }}</div>
            <div class="stat-label">已使用标签</div>
          </div>
          <div class="stat-card unused">
            <div class="stat-value">{{ statistics?.unusedTags || 0 }}</div>
            <div class="stat-label">未使用标签</div>
          </div>
          <div class="stat-card popular">
            <div class="stat-value">{{ statistics?.popularTags || 0 }}</div>
            <div class="stat-label">热门标签</div>
          </div>
        </div>
      </div>

      <!-- 使用统计 -->
      <div class="usage-statistics">
        <h3>使用统计</h3>
        <div class="usage-cards">
          <div class="usage-card">
            <div class="usage-label">平均使用次数</div>
            <div class="usage-value">
              {{ statistics?.avgUseCount?.toFixed(1) || 0 }}
            </div>
          </div>
          <div class="usage-card">
            <div class="usage-label">最大使用次数</div>
            <div class="usage-value">{{ statistics?.maxUseCount || 0 }}</div>
          </div>
          <div class="usage-card">
            <div class="usage-label">总使用次数</div>
            <div class="usage-value">
              {{
                TagManagementUtils.formatUseCount(
                  statistics?.totalUseCount || 0
                )
              }}
            </div>
          </div>
        </div>
      </div>

      <!-- 状态分布 -->
      <div class="status-distribution">
        <h3>状态分布</h3>
        <div class="distribution-chart">
          <div
            v-for="item in statusDistribution"
            :key="item.status"
            class="distribution-item"
          >
            <div class="distribution-bar">
              <div
                class="bar-fill"
                :class="getStatusClass(item.status)"
                :style="{ width: getPercentage(item.count, totalTags) + '%' }"
              />
            </div>
            <div class="distribution-info">
              <span class="status-name">{{ item.statusName }}</span>
              <span class="status-count">{{ item.count }}</span>
              <span class="status-percentage"
                >({{ getPercentage(item.count, totalTags) }}%)</span
              >
            </div>
          </div>
        </div>
      </div>

      <!-- 使用频率分布 -->
      <div class="usage-distribution">
        <h3>使用频率分布</h3>
        <div class="usage-chart">
          <div
            v-for="item in usageDistribution"
            :key="item.usageLevel"
            class="usage-item"
          >
            <div class="usage-bar">
              <div
                class="bar-fill"
                :class="getUsageLevelClass(item.usage_level)"
                :style="{ width: getPercentage(item.count, totalTags) + '%' }"
              />
            </div>
            <div class="usage-info">
              <span class="level-name">{{ item.usageLevel }}</span>
              <span class="level-count">{{ item.count }}</span>
              <span class="level-percentage"
                >({{ getPercentage(item.count, totalTags) }}%)</span
              >
            </div>
          </div>
        </div>
      </div>

      <!-- 颜色分布 -->
      <div class="color-distribution">
        <h3>颜色分布</h3>
        <div class="color-chart">
          <div
            v-for="item in colorDistribution.slice(0, 10)"
            :key="item.color"
            class="color-item"
          >
            <div
              class="color-preview"
              :style="{ backgroundColor: item.color }"
            />
            <div class="color-info">
              <span class="color-name">{{
                item.color_name || item.color
              }}</span>
              <span class="color-count">{{ item.count }} 个标签</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 趋势统计 -->
      <div class="trend-statistics">
        <h3>趋势统计（近6个月）</h3>
        <div class="trend-chart">
          <div class="chart-container">
            <div
              v-for="item in trendStatistics"
              :key="item.month"
              class="trend-item"
            >
              <div class="trend-bars">
                <div
                  class="trend-bar new-tags"
                  :style="{
                    height:
                      getTrendHeight(item.createdCount, maxCreatedCount) + '%'
                  }"
                  :title="`新增: ${item.createdCount}`"
                />
                <div
                  class="trend-bar used-tags"
                  :style="{
                    height:
                      getTrendHeight(item.enabledCount, maxEnabledCount) + '%'
                  }"
                  :title="`启用: ${item.enabledCount}`"
                />
              </div>
              <div class="trend-label">{{ item.month }}</div>
            </div>
          </div>
          <div class="trend-legend">
            <div class="legend-item">
              <div class="legend-color new-tags" />
              <span>新增标签</span>
            </div>
            <div class="legend-item">
              <div class="legend-color used-tags" />
              <span>启用标签</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
        <el-button type="primary" @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { Refresh } from "@element-plus/icons-vue";
import {
  getTagStatisticsApi,
  getTagStatusDistributionApi,
  getTagUsageDistributionApi,
  getTagColorDistributionApi,
  getTagTrendStatisticsApi,
  type TagStatistics,
  type TagStatusDistribution,
  type TagUsageDistribution,
  type TagColorDistribution,
  type TagTrendStatistics,
  TagManagementUtils
} from "@/api/tag-management";

interface Props {
  visible: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false
});

const emit = defineEmits<{
  "update:visible": [value: boolean];
}>();

const dialogVisible = ref(false);
const loading = ref(false);
const statistics = ref<TagStatistics | null>(null);
const statusDistribution = ref<TagStatusDistribution[]>([]);
const usageDistribution = ref<TagUsageDistribution[]>([]);
const colorDistribution = ref<TagColorDistribution[]>([]);
const trendStatistics = ref<TagTrendStatistics[]>([]);

// 监听对话框显示状态
watch(
  () => props.visible,
  newVal => {
    dialogVisible.value = newVal;
    if (newVal) {
      loadStatistics();
    }
  },
  { immediate: true }
);

watch(dialogVisible, newVal => {
  emit("update:visible", newVal);
});

// 计算属性
const totalTags = computed(() => {
  return statistics.value?.totalTags || 0;
});

const maxCreatedCount = computed(() => {
  return Math.max(...trendStatistics.value.map(item => item.createdCount), 1);
});

const maxEnabledCount = computed(() => {
  return Math.max(...trendStatistics.value.map(item => item.enabledCount), 1);
});

// 方法
const loadStatistics = async () => {
  loading.value = true;
  try {
    // 并行加载所有统计数据
    const [statsData, distributionData, usageData, colorData, trendData] =
      await Promise.all([
        getTagStatisticsApi(),
        getTagStatusDistributionApi(),
        getTagUsageDistributionApi(),
        getTagColorDistributionApi(),
        getTagTrendStatisticsApi(6)
      ]);

    if (statsData && statsData.code === 200) {
      statistics.value = statsData.data;
    }

    if (distributionData && distributionData.code === 200) {
      statusDistribution.value = distributionData.data;
    }

    if (usageData && usageData.code === 200) {
      usageDistribution.value = usageData.data;
    }

    if (colorData && colorData.code === 200) {
      colorDistribution.value = colorData.data;
    }

    if (trendData && trendData.code === 200) {
      trendStatistics.value = trendData.data;
    }
  } catch (error) {
    console.error("加载统计数据失败:", error);
    ElMessage.error("加载统计数据失败");
  } finally {
    loading.value = false;
  }
};

const getPercentage = (count: number, total: number): number => {
  if (total === 0) return 0;
  return Math.round((count / total) * 100);
};

const getStatusClass = (status: number): string => {
  return status === 1 ? "enabled" : "disabled";
};

const getUsageLevelClass = (level: string): string => {
  const classMap: Record<string, string> = {
    未使用: "unused",
    低频: "low",
    中频: "medium",
    高频: "high"
  };
  return classMap[level] || "unused";
};

const getTrendHeight = (value: number, max: number): number => {
  if (max === 0) return 0;
  return Math.max((value / max) * 100, 5); // 最小高度5%
};

const handleRefresh = () => {
  loadStatistics();
};

const handleClose = () => {
  dialogVisible.value = false;
};

// 生命周期
onMounted(() => {
  if (props.visible) {
    loadStatistics();
  }
});
</script>

<style scoped>
.statistics-content {
  max-height: 700px;
  overflow-y: auto;
}

.basic-statistics,
.usage-statistics,
.status-distribution,
.usage-distribution,
.color-distribution,
.trend-statistics {
  margin-bottom: 30px;
}

.basic-statistics h3,
.usage-statistics h3,
.status-distribution h3,
.usage-distribution h3,
.color-distribution h3,
.trend-statistics h3 {
  margin: 0 0 16px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.stat-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 16px;
}

.stat-card {
  padding: 20px;
  text-align: center;
  background: #f8f9fa;
  border-left: 4px solid #409eff;
  border-radius: 8px;
}

.stat-card.enabled {
  border-left-color: #67c23a;
}

.stat-card.disabled {
  border-left-color: #f56c6c;
}

.stat-card.used {
  border-left-color: #e6a23c;
}

.stat-card.unused {
  border-left-color: #909399;
}

.stat-card.popular {
  border-left-color: #722ed1;
}

.stat-value {
  margin-bottom: 4px;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.usage-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.usage-card {
  padding: 16px;
  text-align: center;
  background: #f0f9ff;
  border-radius: 8px;
}

.usage-label {
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
}

.usage-value {
  font-size: 20px;
  font-weight: 600;
  color: #1890ff;
}

.distribution-chart,
.usage-chart {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.distribution-item,
.usage-item {
  display: flex;
  gap: 12px;
  align-items: center;
}

.distribution-bar,
.usage-bar {
  flex: 1;
  height: 20px;
  overflow: hidden;
  background: #f0f2f5;
  border-radius: 10px;
}

.bar-fill {
  height: 100%;
  transition: width 0.3s ease;
}

.bar-fill.enabled {
  background: #67c23a;
}

.bar-fill.disabled {
  background: #f56c6c;
}

.bar-fill.unused {
  background: #909399;
}

.bar-fill.low {
  background: #67c23a;
}

.bar-fill.medium {
  background: #e6a23c;
}

.bar-fill.high {
  background: #f56c6c;
}

.distribution-info,
.usage-info {
  display: flex;
  gap: 8px;
  align-items: center;
  min-width: 150px;
}

.status-name,
.level-name {
  font-weight: 500;
  color: #303133;
}

.status-count,
.level-count {
  font-weight: 600;
  color: #409eff;
}

.status-percentage,
.level-percentage {
  font-size: 12px;
  color: #909399;
}

.color-chart {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 12px;
}

.color-item {
  display: flex;
  gap: 12px;
  align-items: center;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 6px;
}

.color-preview {
  width: 24px;
  height: 24px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.color-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.color-name {
  font-weight: 500;
  color: #303133;
}

.color-count {
  font-size: 12px;
  color: #909399;
}

.trend-chart {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.chart-container {
  display: flex;
  gap: 8px;
  align-items: end;
  height: 200px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.trend-item {
  display: flex;
  flex: 1;
  flex-direction: column;
  gap: 8px;
  align-items: center;
}

.trend-bars {
  display: flex;
  gap: 2px;
  align-items: end;
  height: 150px;
}

.trend-bar {
  width: 12px;
  border-radius: 2px 2px 0 0;
  transition: height 0.3s ease;
}

.trend-bar.new-tags {
  background: #67c23a;
}

.trend-bar.used-tags {
  background: #1890ff;
}

.trend-label {
  font-size: 12px;
  color: #606266;
  writing-mode: vertical-rl;
  text-orientation: mixed;
}

.trend-legend {
  display: flex;
  gap: 24px;
  justify-content: center;
}

.legend-item {
  display: flex;
  gap: 8px;
  align-items: center;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 2px;
}

.legend-color.new-tags {
  background: #67c23a;
}

.legend-color.used-tags {
  background: #1890ff;
}

.dialog-footer {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}
</style>
